#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "driver/adc.h"
#include "esp_adc_cal.h"
#include "measuring_lightIntensity.h"
#include "configuration.h"

static const char *TAG = "measuring lightIntensity";
#define DEFAULT_VREF    1100        //Use adc2_vref_to_gpio() to obtain a better estimate
#define NO_OF_SAMPLES   5          //Multisampling

/* ADC初始化 */
void ADCIint()
{
     //配置ADC
    ESP_ERROR_CHECK(adc1_config_width(ADC_WIDTH_BIT_12));//ADC配置为12位
    ESP_ERROR_CHECK(adc1_config_channel_atten(ADC_CHANNEL_4, ADC_ATTEN_DB_11));//GPIO4 通道4 增益11dB(量程0-2600mv)
}
/* 读取光敏电阻分压得出亮度 */
unsigned char measure_brightness()
{
    esp_adc_cal_characteristics_t adc_chars;
    uint32_t adc_reading;
    unsigned int temp;

    //校准ADC
    esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, DEFAULT_VREF, &adc_chars);

    //多次测量取平均值
    adc_reading = 0;
    for (int i = 0; i < NO_OF_SAMPLES; i++) {
        adc_reading += adc1_get_raw((adc1_channel_t)ADC_CHANNEL_4);
    }
    adc_reading /= NO_OF_SAMPLES;

    //数据转换成电压 单位mv   测量值800-2900mv之间
    uint32_t voltage = esp_adc_cal_raw_to_voltage(adc_reading, &adc_chars);
    //ESP_LOGI(TAG, "voltage:%ld",voltage);

    //转成VFD亮度设置值   范围0-240
    temp = (uint16_t)voltage;//截取低16位值用于计算
    if(temp < 800) temp = 800;//测量值太低 补偿到800mv 不然屏太暗
    if(temp >= 2400) temp = 2400;//测量值太高 补偿到2400mv
    temp = temp / 10;//VFD屏亮度分240级

    return (unsigned char)temp;
}